import { Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { In, Repository } from 'typeorm';
import { Role } from './entities/role.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { PageRoleDto } from './dto/page-role.dto';
import { PageResult } from '../common/dto/common.page-result';

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role)
    private readonly roleRepository: Repository<Role>
  ) { }

  async create(createRoleDto: CreateRoleDto) {
    await this.roleRepository.save(createRoleDto);
  }

  async findAll() {
    return await this.roleRepository.find();
  }

  async findOne(id: number) {
    return await this.roleRepository.findOne({ where: { id } });
  }

  async update(id: number, updateRoleDto: UpdateRoleDto) {
    await this.roleRepository.update(id, updateRoleDto);
  }

  async remove(id: number) {
    const role = await this.findOne(id);
    if (role) {
      await this.roleRepository.remove(role);
    } else {
      throw new Error("角色不存在");
    }
  }

  async changeStatus(id: number, status: number) {
    const role = await this.findOne(id);
    if (role) {
      await this.roleRepository.update(id, { status });
    } else {
      throw new Error("角色不存在");
    }
  }

  async page(pageRoleDto: PageRoleDto) {
    const { page, size, name, status, type } = pageRoleDto;
    const query = this.roleRepository.createQueryBuilder("role");

    if (name) {
      query.andWhere("role.name like :name", { name: `%${name}%` });
    }
    if (status) {
      query.andWhere("role.status = :status", { status });
    }
    if (type) {
      query.andWhere("role.type = :type", { type });
    }

    const [list, total] = await query.skip((page - 1) * size).take(size).getManyAndCount();

    return new PageResult(page,size,total,list);
  }
}
